package com.vca.service.service.Impl;

import com.aliyun.oss.*;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.vca.common.exception.VcaException;
import com.vca.common.response.StsTokenResponse;
import com.vca.common.vo.CloudVo;
import com.vca.service.service.OssService;
import com.vca.service.service.SystemConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.util.Date;


/**
 * AsyncServiceImpl 同步到云服务
 */
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private SystemConfigService systemConfigService;

    private static final Logger logger = LoggerFactory.getLogger(OssServiceImpl.class);


    @Override
    public void upload(CloudVo cloudVo, String webPth, String localFile, File file) {
        logger.info("上传文件开始：" + localFile);
        OSS ossClient = new OSSClientBuilder().build(cloudVo.getRegion(), cloudVo.getAccessKey(), cloudVo.getSecretKey());
        try {
            //判断bucket是否存在
            if (!ossClient.doesBucketExist(cloudVo.getBucketName())) {
                ossClient.createBucket(cloudVo.getBucketName());
            }

            if (!file.exists()) {
                logger.info("上传文件" + localFile + "不存在：");
                return;
            }
            PutObjectRequest putObjectRequest = new PutObjectRequest(cloudVo.getBucketName(), webPth, file);
            // 上传文件。
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            logger.info("上传文件 -- 结束：" + putObjectResult.getETag());

        } catch (Exception e) {
            throw new VcaException(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
    }

//    @Override
    public StsTokenResponse getStsToken() {
//    public static void main(String[] args) {

        StsTokenResponse stsTokenResponse = new StsTokenResponse();

        //构建一个阿里云客户端，用于发起请求。
        //设置调用者（RAM用户或RAM角色）的AccessKey ID和AccessKey Secret。
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI5tGeEf1XvTxSt5ERPU6Q", "sfzPi1qjJ59XET1MzBA0JUibeHbvAH");
        IAcsClient client = new DefaultAcsClient(profile);

        //构造请求，设置参数。
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRegionId("cn-shanghai");
        request.setRoleArn("acs:ram::5589102219385282:role/rstg00009");
        request.setRoleSessionName("rstg00009");

        //发起请求，并得到响应。
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            AssumeRoleResponse.Credentials credentials = response.getCredentials();
            stsTokenResponse.setSecurityToken(credentials.getSecurityToken());
            stsTokenResponse.setAccessKeyId(credentials.getAccessKeyId());
            stsTokenResponse.setAccessKeySecret(credentials.getAccessKeySecret());
        } catch (com.aliyuncs.exceptions.ServerException e) {
            e.printStackTrace();
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }


//        try {
//            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
//            DefaultProfile.addEndpoint("", "", "Sts", "oss-cn-shanghai.aliyuncs.com");
//            // 构造default profile（参数留空，无需添加region ID）
//            IClientProfile profile = DefaultProfile.getProfile("", "LTAI5tGeEf1XvTxSt5ERPU6Q", "sfzPi1qjJ59XET1MzBA0JUibeHbvAH");
//            // 用profile构造client
//            DefaultAcsClient client = new DefaultAcsClient(profile);
//            final AssumeRoleRequest request = new AssumeRoleRequest();
//            request.setMethod(MethodType.POST);
//            request.setRoleArn("acs:ram::5192202222067342:role/rstg00010");
//            request.setRoleSessionName("rstg00010");
////            request.setDurationSeconds(durationSeconds);
//            // 针对该临时权限可以根据该属性赋予规则，格式为json，没有特殊要求，默认为空
//            // request.setPolicy(policy); // Optional
//            final AssumeRoleResponse response = client.getAcsResponse(request);
//            AssumeRoleResponse.Credentials credentials = response.getCredentials();
//            stsTokenResponse.setAccessKeyId(credentials.getAccessKeyId());
//            stsTokenResponse.setAccessKeySecret(credentials.getAccessKeySecret());
//            stsTokenResponse.setSecurityToken(credentials.getSecurityToken());
//            return stsTokenResponse;
//        } catch (com.aliyuncs.exceptions.ClientException e) {
//            logger.error("获取阿里云STS临时授权权限失败，错误信息：" + e);
//            return null;
//        }
        return stsTokenResponse;
    }

    /**
     * 获取文件有效路径
     *
     * @param fileSrc
     * @return
     */
    public  String getOssFileUrl(String fileSrc) {

        OSSClient ossClient = new OSSClient(systemConfigService.getValueByKey("alStorageRegion"),systemConfigService.getValueByKey("alAccessKey"), systemConfigService.getValueByKey("alSecretKey"));
        // 上传文件流
        Date expiration = new Date(new Date().getTime() + 60 * 1000);
        // 此处请填写多个Object完整路径，用于一次性获取多个Object的签名URL。
        String objectNameList [] = {"exampleobject.txt","exampleimage.jpg"};
        // 生成URL
        URL url = ossClient.generatePresignedUrl(systemConfigService.getValueByKey("alStorageName"), "objectNameList", expiration);
        return url.toString();
    }


    public static void main(String[] args) {
        OssServiceImpl ossService = new OssServiceImpl();
        StsTokenResponse stsToken = ossService.getStsToken();

        // 以华东1（杭州）的外网Endpoint为例，其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
            // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
            String accessKeyId = stsToken.getAccessKeyId();
            String accessKeySecret = stsToken.getAccessKeySecret();
            // 从STS服务获取的安全令牌（SecurityToken）。
            String securityToken = stsToken.getSecurityToken();
            // 填写Bucket名称，例如examplebucket。
            String bucketName = "bstg00010";
            // 填写Object完整路径，例如exampleobject.txt。Object完整路径中不能包含Bucket名称。
            String objectName = "";
            String pathName = "G:\\file\\test.txt";

            // 从STS服务获取临时访问凭证后，您可以通过临时访问密钥和安全令牌生成OSSClient。
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

            try {
                // 执行OSS相关操作，例如上传、下载文件等。
                // 上传文件，此处以上传本地文件为例介绍。
                // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(pathName));
                ossClient.putObject(putObjectRequest);

                // 下载OSS文件到本地文件。如果指定的本地文件存在则覆盖，不存在则新建。
                // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
//                ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }


    }

